package com.farsunset.cim.sdk.server.slc.handler;

import com.farsunset.cim.sdk.server.coder.AppMessageDecoder;
import com.farsunset.cim.sdk.server.coder.AppMessageEncoder;
import com.farsunset.cim.sdk.server.constant.CIMConstant;
import com.farsunset.cim.sdk.server.constant.ChannelAttr;
import com.farsunset.cim.sdk.server.handler.CIMRequestHandler;
import com.farsunset.cim.sdk.server.handler.LoggingHandler;
import com.farsunset.cim.sdk.server.model.Ping;
import com.farsunset.cim.sdk.server.model.SentBody;
import com.farsunset.cim.sdk.server.slc.handler.CIMNioSocketAcceptor2;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author slc
 * @date 2022/07/12 下午 3:05
 */
public class UdpCIMNioSocketAcceptor extends SimpleChannelInboundHandler<SentBody> {
    protected static final Logger LOGGER = LoggerFactory.getLogger(CIMNioSocketAcceptor2.class);

    private static final int PONG_TIME_OUT_COUNT = 3;
    private final ThreadFactory bossThreadFactory;

    private EventLoopGroup appBossGroup;

    protected final Integer appPort;
    protected final CIMRequestHandler outerRequestHandler;

    protected final ChannelHandler loggingHandler = new LoggingHandler();

    /**
     * 读空闲时间(秒)
     */
    public final int writeIdle = 45;

    /**
     * 写接空闲时间(秒)
     */
    public final int readIdle = 60;

    public UdpCIMNioSocketAcceptor(Builder builder) {
        super();
        this.appPort = builder.appPort;
        this.outerRequestHandler = builder.outerRequestHandler;

        bossThreadFactory = r -> {
            Thread thread = new Thread(r);
            thread.setName(getBossThreadName());
            return thread;
        };

    }

    protected String getBossThreadName() {
        return "udp-nio-boss-";
    }

    protected void createAppEventGroup() {
        appBossGroup = new NioEventLoopGroup(bossThreadFactory);
    }


    public void bind() {
        if (appPort != null) {
            bindAppPort();
        }
    }

    public void destroy(EventLoopGroup bossGroup) {
        if (bossGroup != null && !bossGroup.isShuttingDown() && !bossGroup.isShutdown()) {
            try {
                bossGroup.shutdownGracefully();
            } catch (Exception ignore) {
            }
        }
    }

    public void destroy() {
        this.destroy(appBossGroup);
    }

    protected void bindAppPort() {
        createAppEventGroup();
        Bootstrap bootstrap = createServerBootstrap(appBossGroup);
        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            public void initChannel(Channel ch) {
                ch.pipeline().addLast(new AppMessageDecoder());
                ch.pipeline().addLast(new AppMessageEncoder());
                ch.pipeline().addLast(loggingHandler);
                ch.pipeline().addLast(new IdleStateHandler(readIdle, writeIdle, 0, TimeUnit.SECONDS));
                ch.pipeline().addLast(UdpCIMNioSocketAcceptor.this);
            }
        });

        ChannelFuture channelFuture = bootstrap.bind(appPort).syncUninterruptibly();
        channelFuture.channel().newSucceededFuture().addListener(future -> {
            String logBanner = "\n\n" +
                    "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" +
                    "*                                                                                   *\n" +
                    "*                                                                                   *\n" +
                    "*                   App Udp Server started on port {}.                           *\n" +
                    "*                                                                                   *\n" +
                    "*                                                                                   *\n" +
                    "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n";
            LOGGER.info(logBanner, appPort);
        });
        channelFuture.channel().closeFuture().addListener(future -> this.destroy(appBossGroup));
    }

    protected Bootstrap createServerBootstrap(EventLoopGroup bossGroup) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(bossGroup).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true);
        return bootstrap;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SentBody body) {
        /*
         * 有业务层去处理其他的sentBody
         */
        outerRequestHandler.process(ctx.channel(), body);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ctx.channel().attr(ChannelAttr.ID).set(ctx.channel().id().asShortText());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {

        if (ctx.channel().attr(ChannelAttr.UID) == null) {
            return;
        }

        SentBody body = new SentBody();
        body.setKey(CIMConstant.CLIENT_CONNECT_CLOSED);
        outerRequestHandler.process(ctx.channel(), body);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {

        if (!(evt instanceof IdleStateEvent)) {
            return;
        }

        IdleStateEvent idleEvent = (IdleStateEvent) evt;

        String uid = ctx.channel().attr(ChannelAttr.UID).get();

        /*
         * 关闭未认证的连接
         */
        if (idleEvent.state() == IdleState.WRITER_IDLE && uid == null) {
            ctx.close();
            return;
        }

        /*
         * 已经认证的连接发送心跳请求
         */
        if (idleEvent.state() == IdleState.WRITER_IDLE && uid != null) {

            Integer pingCount = ctx.channel().attr(ChannelAttr.PING_COUNT).get();
            ctx.channel().attr(ChannelAttr.PING_COUNT).set(pingCount == null ? 1 : pingCount + 1);

            ctx.channel().writeAndFlush(Ping.getInstance());

            return;
        }

        /*
         * 如果心跳请求发出30秒内没收到响应，则关闭连接
         */
        Integer pingCount = ctx.channel().attr(ChannelAttr.PING_COUNT).get();
        if (idleEvent.state() == IdleState.READER_IDLE && pingCount != null && pingCount >= PONG_TIME_OUT_COUNT) {
            ctx.close();
            LOGGER.info("{} pong timeout.", ctx.channel());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        LOGGER.warn("EXCEPTION", cause);
    }

    protected EventLoopGroup getAppBossGroup() {
        return appBossGroup;
    }


    public static class Builder {
        private Integer appPort;
        private CIMRequestHandler outerRequestHandler;

        public Builder setAppPort(Integer appPort) {
            this.appPort = appPort;
            return this;
        }

        /**
         * 设置应用层的sentBody处理handler
         */
        public Builder setOuterRequestHandler(CIMRequestHandler outerRequestHandler) {
            this.outerRequestHandler = outerRequestHandler;
            return this;
        }

        public UdpCIMNioSocketAcceptor build() {
            return new UdpCIMNioSocketAcceptor(this);
        }

    }
}
